<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>商品详情</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .product-image {
            max-height: 400px;
            object-fit: contain;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .product-info {
            padding: 2rem;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .rating-stars {
            position: relative;
            display: inline-block;
            font-size: 1.2rem;
            letter-spacing: 2px;
        }
        .rating-stars::before {
            content: '★★★★★';
            color: #ddd;
        }
        .rating-stars::after {
            content: '★★★★★';
            position: absolute;
            left: 0;
            top: 0;
            color: #ffc107;
            overflow: hidden;
        }
        .rating-stars[data-rating="1"]::after { width: 20%; }
        .rating-stars[data-rating="2"]::after { width: 40%; }
        .rating-stars[data-rating="3"]::after { width: 60%; }
        .rating-stars[data-rating="4"]::after { width: 80%; }
        .rating-stars[data-rating="5"]::after { width: 100%; }
        .review-card {
            border: none;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            margin-bottom: 1.5rem;
            transition: all 0.3s ease;
        }
        .review-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .review-header {
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 0.75rem;
            margin-bottom: 0.75rem;
        }
        .review-content {
            color: #555;
            line-height: 1.6;
        }
        .review-date {
            color: #888;
            font-size: 0.85rem;
        }
        .quantity-input {
            width: 80px;
            text-align: center;
        }
    </style>
</head>
<body>
<div th:replace="~{common/customer-navbar :: navbar}"></div>

<div class="container mt-4">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="/customer/products">商品列表</a></li>
            <li class="breadcrumb-item active" aria-current="page">商品详情</li>
        </ol>
    </nav>

    <div class="row">
        <div class="col-md-6">
            <img th:src="${product.photo != null ? product.photo : '/images/default-product.jpg'}"
                 class="img-fluid product-image" alt="商品图片">
        </div>
        <div class="col-md-6 product-info">
            <h2 th:text="${product.productName}">商品名称</h2>
            <div class="mb-3">
                <span class="badge bg-secondary" th:text="${product.parentCategoryName + ' > ' + product.categoryName}">分类</span>
            </div>
            <p class="text-muted" th:text="${product.description}">商品描述</p>

            <div class="d-flex align-items-center mb-3">
                <h3 class="text-primary mb-0" th:text="'¥' + ${product.price}">¥99.00</h3>
                <span class="badge bg-success ms-3" th:text="'库存: ' + ${product.rest}">库存: 10</span>
            </div>

            <hr>

            <div class="mb-3">
                <label for="quantity" class="form-label">购买数量</label>
                <input type="number" class="form-control" id="quantity" min="1" th:max="${product.rest}" value="1">
            </div>

            <div class="d-grid gap-2">
                <button class="btn btn-primary" type="button" id="addToCartBtn" th:data-product-id="${product.productId}">加入购物车</button>
                <button class="btn btn-outline-primary" type="button">立即购买</button>
            </div>

            <script>
                document.getElementById('addToCartBtn').addEventListener('click', function() {
                    const productId = document.getElementById('addToCartBtn').getAttribute('data-product-id');
                    const quantity = parseInt(document.getElementById('quantity').value);
                    const maxQuantity = parseInt(document.getElementById('quantity').max);

                    // 验证数量
                    if (isNaN(quantity) || quantity <= 0) {
                        alert('请输入有效的数量');
                        return;
                    }

                    if (quantity > maxQuantity) {
                        alert(`数量不能超过库存量: ${maxQuantity}`);
                        return;
                    }

                    // 显示加载状态
                    const btn = document.getElementById('addToCartBtn');
                    const originalText = btn.textContent;
                    btn.disabled = true;
                    btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';

                    fetch('/api/cart', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        credentials: 'include',
                        body: JSON.stringify({
                            productId: productId,
                            quantity: quantity
                        })
                    })
                    .then(async response => {
                        const data = await response.json();
                        if (!response.ok) {
                            throw new Error(data.message || '请求失败');
                        }
                        return data;
                    })
                    .then(data => {
                        if (data.success) {
                            // 使用更美观的通知代替alert
                            const toast = document.createElement('div');
                            toast.className = 'position-fixed bottom-0 end-0 p-3';
                            toast.innerHTML = `
                                <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                                    <div class="toast-header bg-success text-white">
                                        <strong class="me-auto">成功</strong>
                                        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                                    </div>
                                    <div class="toast-body">
                                        ${data.message}
                                    </div>
                                </div>
                            `;
                            document.body.appendChild(toast);
                            setTimeout(() => toast.remove(), 3000);

                            // 更新购物车数量显示
                            const cartBadge = document.querySelector('.cart-badge');
                            if (cartBadge) {
                                const currentCount = parseInt(cartBadge.textContent) || 0;
                                cartBadge.textContent = currentCount + quantity;
                            }
                        } else {
                            throw new Error(data.message || '操作失败');
                        }
                    })
                    .catch(error => {
                        const errorMsg = error.message || '操作失败，请稍后再试';
                        if (errorMsg.includes('未登录')) {
                            window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
                        } else if (errorMsg.includes('库存不足')) {
                            // 库存不足时自动调整数量
                            document.getElementById('quantity').value = maxQuantity;
                            alert(`库存不足，已自动调整为最大可用数量: ${maxQuantity}`);
                        } else {
                            alert(errorMsg);
                        }
                    })
                    .finally(() => {
                        btn.disabled = false;
                        btn.textContent = originalText;
                    });
                });
            </script>
        </div>
    </div>
</div>


    <!-- 商品评价区域 -->
    <div class="row mt-5">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h3>商品评价</h3>
                <div id="review-stats" class="d-flex align-items-center">
                    <div class="me-3">
                        <span class="fs-4 fw-bold text-warning" id="average-rating">0.0</span>
                        <span class="text-muted">/5</span>
                    </div>
                    <div>
                        <div class="text-muted" id="total-reviews">0条评价</div>
                    </div>
                </div>
            </div>

            <div id="reviews-container">
                <div class="text-center py-5" id="loading-reviews">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
                <div id="no-reviews" class="text-muted py-4" style="display: none;">暂无评价</div>
                <div id="reviews-list" class="list-group"></div>
            </div>
        </div>
    </div>


<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
<script>
    // 加载商品评价
    document.addEventListener('DOMContentLoaded', function() {
        const productId = document.getElementById('addToCartBtn').getAttribute('data-product-id');
        loadProductReviews(productId);
    });

    function loadProductReviews(productId) {
        fetch(`/api/products/${productId}/reviews`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取评价失败');
                }
                return response.json();
            })
            .then(data => {
                document.getElementById('loading-reviews').style.display = 'none';

                // 更新评价统计信息
                document.getElementById('average-rating').textContent = data.averageRating;
                document.getElementById('total-reviews').textContent = `${data.totalReviews}条评价`;

                if (data.reviews.length === 0) {
                    document.getElementById('no-reviews').style.display = 'block';
                    return;
                }

                const reviewsList = document.getElementById('reviews-list');
                data.reviews.forEach(review => {
                    const reviewItem = document.createElement('div');
                    reviewItem.className = 'card review-card';
                    reviewItem.innerHTML = `
                        <div class="card-body">
                            <div class="review-header">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">${review.userName || '匿名用户'}</h5>
                                    <small class="review-date">${new Date(review.createTime).toLocaleString()}</small>
                                </div>
                                <div class="rating-stars mt-2" data-rating="${review.rate}"></div>
                            </div>
                            <div class="review-content mt-3">
                                <p>${review.comment || '此用户没有填写评价内容'}</p>
                            </div>
                        </div>
                    `;
                    reviewsList.appendChild(reviewItem);
                });
            })
            .catch(error => {
                console.error('加载评价失败:', error);
                document.getElementById('loading-reviews').style.display = 'none';
                document.getElementById('no-reviews').textContent = '加载评价失败，请刷新重试';
                document.getElementById('no-reviews').style.display = 'block';
            });
    }
</script>
</body>
</html>